package cn.dqy.gotanserver.support;

import cn.dqy.gotanserver.config.ConfigClass;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatusStatisticsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendStatusStatisticsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class SmsSupport implements ApplicationContextAware {
    static Logger logger = LoggerFactory.getLogger(SmsSupport.class);

    Queue<String> smsBatchQueue=new ArrayDeque<>();

    @Autowired
    ConfigClass configClass;

    @Resource(name="threadPool")
    ThreadPoolExecutor threadPoolExecutor;

    public void addSmsContent(String addr){
        synchronized (SmsSupport.class){
            smsBatchQueue.add(addr);
        }
    }

    public SmsClient initClient(){
        Credential cred = new Credential(configClass.getSmsSecretId(), configClass.getSmsSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setConnTimeout(30);
        httpProfile.setEndpoint("sms.tencentcloudapi.com");

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod("HmacSHA256");
        clientProfile.setHttpProfile(httpProfile);
        SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);

        return client;
    }

    public String statisticsSmsData(){
        try{
            logger.info("统计短信发送数据");

            SmsClient client = initClient();

            SendStatusStatisticsRequest req = new SendStatusStatisticsRequest();

            String sdkAppId = configClass.getSmsAppId();
            req.setSmsSdkAppId(sdkAppId);

            // 设置拉取最大条数，最多100条
            req.setLimit(10l);
            req.setOffset(0l);
            /* 开始时间，yyyymmddhh 需要拉取的起始时间，精确到小时 */
            String beginTime = "2019071100";
            req.setBeginTime(beginTime);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyymmddhh");
            String endTime = sdf.format(new Date());
            req.setEndTime(endTime);
            SendStatusStatisticsResponse res = client.SendStatusStatistics(req);
            String jsonStr = SendStatusStatisticsResponse.toJsonString(res);
            logger.info("拉取短信成功 res={}",jsonStr);
            return jsonStr;
        }catch (TencentCloudSDKException e) {
            e.printStackTrace();
            logger.error("统计短信发送数据 ",e);
        }
        return "统计短信发送数据失败";
    }

    private void sendSms(String content){
        try {
            logger.info("开始发送短信");

            SmsClient client = initClient();

            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppId(configClass.getSmsAppId());
            req.setSignName(configClass.getSmsSignName());
            req.setTemplateId(configClass.getSmsTemplateId());
            String[] templateParamSet = {content};
            req.setTemplateParamSet(templateParamSet);
            String[] phoneNumberSet = {"+86" + configClass.getSmsSendPhton()};
            req.setPhoneNumberSet(phoneNumberSet);
            /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
            String sessionContext = "null";
            req.setSessionContext(sessionContext);

            SendSmsResponse res = client.SendSms(req);

            // 输出json格式的字符串回包
            logger.info("短信发送成功 返回结果 {}",SendSmsResponse.toJsonString(res));
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            logger.error("短信发送异常 ",e);
        }
    }

    private void smsBatchSend(){
        StringBuilder builder=new StringBuilder();
        if(smsBatchQueue.size()==0) {
            logger.info("待发送短信内容为空，无需发送短信");
            return;
        }
        while (!smsBatchQueue.isEmpty()){
            builder.append(smsBatchQueue.poll() + ",");
        }
        String content = builder.toString();
        logger.info("短信聚合内容 : {}",content);
        //sendSms(content);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("短信内容聚合发送线程启动...");
        threadPoolExecutor.execute(()->{
            while (true){
                try {
                    Thread.sleep(configClass.getSmsCycle());
                    synchronized (SmsSupport.class) {
                        smsBatchSend();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
